<template>
  <div class="detention-count-chart">
    <div class="chart-header">
      <h5>在押人数统计</h5>

    </div>

    <div class="chart-container">
      <!-- 柱状图表容器 -->
      <div class="bar-chart-wrapper" ref="combinedChartContainer"></div>
    </div>
  </div>
</template>

<script>
import { Chart } from '@antv/g2'

export default {
  name: 'DetentionCountChart',
  data() {
    return {
      barChart: null,
      totalDetentionCount: 0,
      trendData: [], // 折线图数据
      areaData: [], // 条形图数据
      selectedArea: null
    }
  },
  mounted() {
    this.generateMockData()
    this.initBarChart()
    // this.startDataUpdate()
  },
  beforeDestroy() {
    if (this.barChart) {
      this.barChart.destroy()
    }
    if (this.updateTimer) {
      clearInterval(this.updateTimer)
    }
  },
  methods: {
    generateMockData() {
      // 生成折线图数据 - 12个月的在押人数趋势
      const months = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
      this.trendData = []
      let baseCount = 850

      months.forEach((month, index) => {
        const seasonalFactor = Math.sin((index / 12) * 2 * Math.PI) * 30
        const trendFactor = index * 15
        const randomFactor = (Math.random() - 0.5) * 50

        const count = Math.round(baseCount + seasonalFactor + trendFactor + randomFactor)
        this.trendData.push({
          month,
          count,
          date: `2024-${String(index + 1).padStart(2, '0')}`
        })
      })

      // 生成条形图数据 - 11个监区的在押人数
      this.areaData = []
      let totalCount = 0

      for (let i = 1; i <= 11; i++) {
        const baseCount = 60 + Math.floor(Math.random() * 40)
        const usageRatio = 0.7 + Math.random() * 0.3 // 70%-100%使用率
        const count = Math.floor(baseCount * usageRatio)

        this.areaData.push({
          area: `第${i}监区`,
          count,
          capacity: baseCount,
          usageRate: Number((usageRatio * 100).toFixed(1))
        })

        totalCount += count
      }

      this.totalDetentionCount = totalCount
    },

    initBarChart() {
      this.$nextTick(() => {
        if (this.barChart) {
          this.barChart.destroy()
        }

        const container = this.$refs.combinedChartContainer
        if (!container) return

        this.barChart = new Chart({
          container,
          autoFit: true,
          height: 250
        })

        // 准备柱状图数据 - 11个监区的在押人数
        const barData = this.areaData.map(area => ({
          area: area.area,
          count: area.count,
          usageRate: area.usageRate,
          areaName: area.area,
          capacity: area.capacity
        }))
        console.log(barData)
        this.barChart.data(barData)

        // 柱状图 - 监区在押人数
        this.barChart
          .interval()
          .encode('x', 'area')
          .encode('y', 'count')
          .tooltip((data) => ({
            name: data.areaName,
            value: `${data.count}/${data.capacity}人 (${data.usageRate}%)`
          }))
          .axis('y', {
            title: false,
            titleFill: '#00ffff',
            labelFill: '#fff',
            labelFontSize: 12,
            grid: {
              lineStroke: 'rgba(255, 255, 255, 0.1)',
              lineWidth: 1
            }
          })
          .axis('x', {
            title: false,
            labelFill: '#fff',
            labelFontSize: 11,
            labelRotate: 45,
            grid: false
          })
          .animate('enter', { type: 'growInY', duration: 1000 })

        // 添加点击事件
        this.barChart.on('element:click', (event) => {
          if (event.data && event.data.data) {
            const data = event.data.data;
            if (data.areaName) {
              this.handleBarClick({
                area: data.areaName,
                count: data.count,
                usageRate: data.usageRate,
                capacity: data.capacity
              });
            }
          }
        });

        this.barChart.theme({
          background: 'transparent',
          view: {
            viewFill: 'transparent'
          }
        });

        this.barChart.render();
      });
    },

    handleBarClick(data) {
      this.selectedArea = this.selectedArea === data.area ? null : data.area

      // 重新渲染柱状图以更新选中状态
      this.initBarChart()

      // 这里可以触发其他交互，比如显示详情面板、跳转等
      console.log('选中监区:', data)
      // 可以发射事件给父组件
      this.$emit('area-selected', data)
    },

    startDataUpdate() {
      this.updateTimer = setInterval(() => {
        this.updateData()
      }, 10000) // 每10秒更新一次
    },

    updateData() {
      // 更新柱状图数据
      this.areaData.forEach(area => {
        const change = (Math.random() - 0.5) * 5
        area.count = Math.max(0, Math.min(area.capacity, Math.round(area.count + change)))
        area.usageRate = Number(((area.count / area.capacity) * 100).toFixed(1))
      })

      // 重新计算总数
      this.totalDetentionCount = this.areaData.reduce((sum, area) => sum + area.count, 0)

      // 更新柱状图
      if (this.barChart) {
        // 重新准备柱状图数据
        const barData = this.areaData.map(area => ({
          area: area.area,
          count: area.count,
          usageRate: area.usageRate,
          areaName: area.area,
          capacity: area.capacity
        }))

        this.barChart.changeData(barData)
      }
    }
  }
}
</script>

<style scoped>
.detention-count-chart {
  overflow: hidden;
  height: 100%;
  display: flex;
  flex-direction: column;
  background: linear-gradient(145deg,
    rgba(0, 80, 120, 0.12) 0%,
    rgba(0, 100, 140, 0.08) 30%,
    rgba(0, 60, 100, 0.05) 70%,
    rgba(0, 90, 130, 0.08) 100%
  ),
  radial-gradient(circle at 30% 30%, rgba(255, 255, 255, 0.08) 0%, transparent 50%),
  rgba(0, 0, 0, 0.5);
  border-radius: 12px;
  padding: 20px;
  border: 1px solid rgba(0, 100, 150, 0.3);
  backdrop-filter: blur(10px);
  box-shadow:
    0 8px 32px rgba(0, 100, 150, 0.2),
    inset 0 1px 0 rgba(255, 255, 255, 0.1);
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  flex-shrink: 0;
}

.chart-header h5 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  background: linear-gradient(45deg,
    rgba(0, 120, 160, 0.9) 0%,
    rgba(0, 100, 140, 0.8) 50%,
    rgba(0, 80, 120, 0.7) 100%
  );
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  text-shadow: 0 0 10px rgba(0, 100, 150, 0.4);
}

.total-indicator {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.total-value {
  font-size: 28px;
  font-weight: bold;
  color: #00ffff;
  text-shadow: 0 0 15px rgba(0, 255, 255, 0.6);
}

.total-label {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.7);
}

.chart-container {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.bar-chart-wrapper {
  flex: 1;
  border-radius: 8px;
  overflow: hidden;
  min-height: 400px;
}

</style>
